import captcha
from celery.worker.state import requests
from django.shortcuts import render
from kombu.utils import json
from . utils import *
from myapp.models import User,Social
from myapp.serializers import UserS
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_jwt.serializers import jwt_encode_handler
import re
from redis import Redis
# Create your views here.
import random,string,redis

# 判断用户名
class CheckUsername(APIView):
    def get(self,request,username):
        if not re.findall(r'^[a-zA-Z]\w{4,15}$',username):
            return Response({'code':404,'msg':'验证码格式不匹配'})

        if User.objects.filter(username=username):
            return Response({'code':204,'msg':'用户名重复'})
        else:
            return Response({'code':200,'msg':'ok'})

# 判断手机号
class CheckMobile(APIView):
    def get(self,request,mobile):
        if not re.findall(r'^1[3-9]\d{9}$',mobile):
            return Response({'code':404,'msg':'电话格式不匹配'})

        if User.objects.filter(mobile=mobile):
            return Response({'code':204,'msg':'电话号码重复'})
        else:
            return Response({'code':200,'msg':'ok'})

#  判断密码
class CheckPassword(APIView):
    def post(self,request):
        password = request.data.get('password')
        if not re.findall(r'^\w{6,15}$',password):
              return Response({'code':400,'msg':"密码格式错误"})
        else:
            return Response({'code':200,'msg':'ok',})

from captcha.image import ImageCaptcha
from django.http import HttpResponse
# 生成图形验证码
class ImgCode(APIView):
    def get(self,request,uuid):
        code = ''.join(random.sample(string.ascii_letters+string.digits,4))
        print(code)
        cap = ImageCaptcha()
        img_code = cap.generate(code)
        r = redis.Redis(host='localhost',port=6379,password=123456,db=0)
        r.set(uuid,code,ex=120)
        r.close()
        return HttpResponse(img_code,content_type='image/png')

# 判断图形验证码是否正确
class CheckCode(APIView):
    def get(self,request):
        uuid = request.query_params.get('imageCodeID')
        img_code = request.query_params.get('imageCode')
        r = redis.Redis(host='localhost',password=123456,port=6379,db=0)
        r_code = r.get(uuid)
        if not r_code:
            return Response({'code':204,'msg':'验证码过期'})
        if img_code.lower()==r_code.decode().lower():
            return Response({'code':200,'msg':'ok'})
        else:
            return Response({'code':404,'msg':'验证码错误'})

# 生成短信验证码
class YZMView(APIView):
    def get(self, request):
        mobile = request.query_params.get('mobile')
        data =random.randint(000000,999999)
        if mobile:
            snd = send_sms_code(mobile,data)
        else:
            return Response({'code':400,'msg':'参数错误'})
        status_code = json.loads(snd)['statusCode']
        if status_code == '000000' or status_code == '111141':
            re = Redis()
            re.setex("mobile",600,data)
            return Response({'code':200,'msg':'发送成功'})
        return Response({'code':400,'msg':'发送失败'})

class LoginView(APIView):
    def post(self, request):
        mobile = request.data.get('mobile')
        sms_code = request.data.get('sms_code')
        r = Redis()
        re = r.get(mobile)
        if sms_code==re:
            return Response({'code':200,'msg':'验证码正确'})
        phone = User.objects.filter(mobile=mobile).first()
        r = r'^1[3-9]\d{9}$'
        if not re.findall(r,mobile):
            return Response({'code':400,'msg':'手机号格式不对'})
        if phone:
            payload = {
                'mobile': phone.mobile
            }
            token = jwt_encode_handler(payload)
            return Response({'code':200,'msg':'登录成功'})
        else:
            try:
                mobile_info = User.objects.create(mobile=mobile)
                payload = {
                    'mobile':mobile_info.mobile
                }
                token = jwt_encode_handler(payload)
                return Response({'code':201,'msg':'注册成功','data':{'mobile':mobile_info.mobile,'token':token}})
            except Exception as e:
                print(e)
                return Response({'code':400,'msg':'登录失败'})

def get_weibo_userinfo(access_token):
    url = 'https://api.weibo.com/oauth2/get_token_info'
    data = {
        'access_token': access_token,
    }
    res = requests.post(url=url, data=data).text
    print('<218>Access 的相关信息:', res)
    return json.loads(res)['uid']


def get_weibo_accesstoken(code):
    # 获取 access_token 的必要参数 ↓
    url = 'https://api.weibo.com/oauth2/access_token'
    data = {
        'client_id': '2851645393',   # 创建应用的 App Key
        'client_secret': '646691419daa4bcb80c1bd95164b583',   # 创建应用的 App Secret
        'grant_type': 'authorization_code',   # 文档 写死
        'redirect_uri': 'http://127.0.0.1:8080/course_index',   #  回调地址
        'code': code    # 接收到的编码
    }
    # 构造 post 对 weibo 的 url 发起请求
    res = requests.post(url=url, data=data).text
    print('<206>Token 换取的结果：', res)
    # 得到请求转换为 字典 然后 取 键
    return json.loads(res)['access_token']

# 接收 微博回调页面 发送的 code
class Get_WeiBo_Code(APIView):
    def post(self, request):
        code = request.data['code']
        print(code)
        # 通过 code 获取授权的 access_token
        access_token = get_weibo_accesstoken(code)
        uid = get_weibo_userinfo(access_token)
        # 从数据库 取 数据判断 用户是否 注册过
        try:
            s = Social.objects.get(
                third_party=3,  # 直接绑定微博
                uid=uid
            )
        except:
            # 当 抛出异常就代表没有（微博用户）
            # 给出对应的 数据
            return Response({
                'code': '10030',
                'message': '用户不存在，请绑定本站',
                'uid': uid
            })
        else:
            # 没有 异常 代表曾经注册过
            # 生成 token 保存登录状态
            data = {
                'id': s.user.id,
                'email': s.user.email
            }
            jwt_token = (data)
            # 发送到前台
            return Response({
                'code': 200,
                'message': '您是本站的老用户',
                'token': jwt_token,
                'email': s.user.email
            })

class GetUser(APIView):
    def get(self,request):
        user_data = User.objects.all()
        ser = UserS(user_data,many=True)
        return Response(ser.data)

